#include "plane.hpp"

#include <iostream>
using namespace std;

Plane::Plane(Point3D nposition1,Point3D nposition2, Point3D nposition3, Material nMat):RTobject(nposition1, nMat), position2(nposition2), position3(nposition3)
{
	normalVect.x=position.y*(position2.z-position3.z)+position2.y*(position3.z-position.z)+position3.y*(position.z-position2.z);
	normalVect.y=position.z*(position2.x-position3.x)+position2.z*(position3.x-position.x)+position3.z*(position.x-position2.x);
	normalVect.z=position.x*(position2.y-position3.y)+position2.x*(position3.y-position.y)+position3.x*(position.y-position2.y);
	normalVect=normalize(normalVect);
	D = -(normalVect&ConvertToVector(position)); // normalVect & A 
}

bool Plane::Intersect(Ray& intersectRay, double& t)
{
	using namespace Defined;
	//Calculating intersection for plane
	//First, check if the ray parallel
	double cosAng = normalVect&intersectRay.direction;
	if (cosAng > -EPS && cosAng < EPS) return false;
	//Calculate t & check is intersection point visible
	double lamda = normalVect&ConvertToVector(intersectRay.startPoint); 
	t = -(D + lamda)/cosAng;

	return t > GeomThreshold;
}

Color Plane::Trace(Ray& viewRay,Point3D lightPos,double& dist)
{
	// calculate the location of the intersection between the sphere and the ray. 
	Vector3D intersection=viewRay.startPoint + dist*viewRay.direction;
	
	// calculate direction from the intersection to light
	Vector3D lightDirection = normalize(lightPos-intersection);   
 	double lightCoef1=lightDirection & normalVect; //AKA cos1   
 	double lightCoef2=lightDirection & (-normalVect); //Aka cos2
	
	if (lightCoef1<lightCoef2) lightCoef1=lightCoef2;
	
	if (lightCoef1<Defined::EPS) lightCoef1=0;
	
	if (objTex!=NULL)
		objTex->ApplyTexture(objMat.objectColor, intersection);

	Color tColor = objMat.objectColor*lightCoef1; 
	return tColor; 

}
